<template>
	<basic-container>
		<avue-crud
			:option="option"
			:data="data"
			ref="crud"
			v-model="form"
			:table-loading="loading"
			:permission="permissionList"
			@row-del="rowDel"
			@row-update="rowUpdate"
			@row-save="rowSave"
			:before-open="beforeOpen"
			:page="page"
			@refresh-change="refreshChange"
			@search-change="searchChange"
			@search-reset="searchReset"
			@current-change="currentChange"
			@size-change="sizeChange"
			@on-load="onLoad"
		>
			<template slot-scope="{ row }" slot="status">
				<el-switch @change="rowSwitchChange(row)" v-model="row.status" active-value="ENABLE" inactive-value="DISABLE"></el-switch>
			</template>
			<template slot-scope="{ row }" slot="customerService">
				<el-switch @change="customerServiceSwitchChange(row)" v-model="row.customerService" :active-value="true" :inactive-value="false"></el-switch>
			</template>
			<template slot="search">
				<el-col :span="7" style="margin-top: 7px;">
					<el-form-item size="mini" label="账户/姓名/手机号" prop="supplierCode" label-width="130px">
						<el-input v-model="keySearch" style="width:100%;"></el-input>
					</el-form-item>
				</el-col>
			</template>

			<template slot-scope="{ row }" slot="menuLeft">
				<el-button type="primary" size="mini" @click="addUser">新增用户</el-button>
			</template>

			<template slot-scope="{ row, type, size }" slot="menu">
				<el-button :type="type" :size="size" icon="el-icon-thumb" @click="rowRoles(row)">分配角色</el-button>
				<el-button :type="type" :size="size" icon="el-icon-refresh-right" @click="rowReset(row)">重置</el-button>
				<el-button :type="type" :size="size" icon="el-icon-edit" @click="rowEdit(row)">编辑</el-button>
			</template>
		</avue-crud>
		<el-dialog title="分配角色" :visible.sync="box" width="40%">
			<el-scrollbar style="height:400px">
				<el-tree
					:data="rolesTree"
					show-checkbox
					node-key="id"
					ref="tree"
					default-expand-all
					:default-checked-keys="rolesKeys"
					:props="{ label: 'name', value: 'id' }"
				></el-tree>
			</el-scrollbar>
			<span slot="footer"><el-button type="primary" size="small" :disabled="isDisabled" @click="handleSetRoles">确 定</el-button></span>
		</el-dialog>
		<el-dialog title="新增用户" :visible.sync="addIsShow">
			<avue-form :option="addUserOption" ref="diaformRef" v-model="userFrom">
				<template slot="menuForm">
					<el-button type="primary" @click="btnSubmit" :loading="addLoadU">提 交</el-button>
					<el-button @click="handleEmpty">清 空</el-button>
				</template>
			</avue-form>
		</el-dialog>
		<el-dialog title="编辑用户信息" :visible.sync="editIsShow">
			<avue-form :option="editAddUserOption" ref="diaEditFormRef" v-model="editUserFrom">
				<template slot="menuForm">
					<el-button type="primary" @click="editBtnSubmit" :loading="editLoadU">提 交</el-button>
					<el-button @click="editHandleEmpty">清 空</el-button>
				</template>
			</avue-form>
		</el-dialog>
	</basic-container>
</template>
<script>
import { getList, getUser, remove, update, add, setRoles, changeStatus, customerServiceStatus, resetPassword } from '@/api/subAccount/subMgr';
import { getRolesTree } from '@/api/subAccount/subRoles';
import { mapGetters } from 'vuex';
import { testPhone,testPassWord ,testAccountName} from '@/util/util';
var testAccount = (rule, value, callback) => {
	if (value === '') {
		callback(new Error('请输入店铺账号'));
	} else if (!/^([a-zA-Z0-9]){1,16}$/.test(value)) {
		callback(new Error('店铺账号应为1-16个英文、数字'));
	} else {
		callback();
	}
};
export default {
	watch: {
		addIsShow(val) {
			if (!val) {
				this.$nextTick(() => {
					this.$refs['diaformRef'].resetForm();
				});
				this.addLoadU = false;
			}
		},
		editIsShow(val) {
			if (!val) {
				this.$nextTick(() => {
					this.$refs['diaEditFormRef'].resetForm();
				});
				this.editLoadU = false;
			}
		}
	},
	data() {
		return {
			isDisabled: true,
			editLoadU: false,
			addLoadU: false,
			flag: true,
			keySearch: '',
			userFrom: {},
			editUserFrom: {},
			addUserOption: {
				submitBtn: false,
				emptyBtn: false,
				column: [
					{
						label: '账号',
						prop: 'account',
						search: true,
						fixed: true,
						rules: [
							{
								required: true,
								message: '请输入账号',
								trigger: 'blur'
							},
							{
							    validator: testAccount,
							    trigger: 'blur'
							},
						]
					},
					{
						label: '密码',
						prop: 'password',
						type: 'password',
						autocomplete: 'off',
						rules: [
							{
								required: true,
								message: '请输入密码',
								trigger: 'blur'
							},
							{
							    validator: testPassWord,
							    trigger: 'blur'
							},
						]
					},
					{
						label: '姓名',
						prop: 'name',
						rules: [
							{
								required: true,
								message: '请输入姓名',
								trigger: 'blur'
							},
							{
							    validator: testAccountName,
							    trigger: 'blur'
							},
						]
					},
					{
						label: '电话',
						prop: 'phone',
						width: 120,
						rules: [
							{
								required: true,
								message: '请输入电话',
								trigger: 'blur'
							},
							{
								validator: testPhone,
								trigger: 'blur'
							}
						]
					},
					// {
					//     label: "电子邮箱",
					//     prop: "email",
					//     hide: true,
					//     overHidden: true
					// },
					{
						label: '用户生日',
						type: 'date',
						prop: 'birthday',
						format: 'yyyy-MM-dd',
						valueFormat: 'yyyy-MM-dd',
						hide: true
						// rules: [
						// {
						//     required: true,
						//     message: "请输入用户生日",
						//     trigger: "change"
						// },
						// {
						//     validator: testBirthday,
						//     trigger: "blur"
						// },
						// ]
					},
					{
						label: '用户性别',
						prop: 'sex',
						type: 'radio',
						// rules: [{
						//     required: true,
						//     message: "请选择性别",
						//     trigger: "blur"
						// }],
						dicData: [
							{
								label: '男',
								value: '1'
							},
							{
								label: '女',
								value: '0'
							}
						],
						// valueDefault: '1',
						hide: true
					}
				]
			},
			editAddUserOption: {
				submitBtn: false,
				emptyBtn: false,
				column: [
					{
						label: '账号',
						prop: 'account',
						search: true,
						fixed: true,
						rules: [
							{
								required: true,
								message: '请输入账号',
								trigger: 'blur'
							},
							{
							    validator: testAccount,
							    trigger: 'blur'
							},
						]
					},
					{
						label: '姓名',
						prop: 'name',
						rules: [
							{
								required: true,
								message: '请输入姓名',
								trigger: 'blur'
							},
							{
							    validator: testAccountName,
							    trigger: 'blur'
							},
						]
					},
					{
						label: '电话',
						prop: 'phone',
						width: 120,
						rules: [
							{
								required: true,
								message: '请输入电话',
								trigger: 'blur'
							},
							{
								validator: testPhone,
								trigger: 'blur'
							}
						]
					},
					// {
					//     label: "电子邮箱",
					//     prop: "email",
					//     hide: true,
					//     overHidden: true
					// },
					{
						label: '用户生日',
						type: 'date',
						prop: 'birthday',
						format: 'yyyy-MM-dd hh:mm:ss',
						valueFormat: 'yyyy-MM-dd hh:mm:ss',
						hide: true
						// rules: [
						// {
						//     required: true,
						//     message: "请输入用户生日",
						//     trigger: "change"
						// },
						// {
						//     validator: testBirthday,
						//     trigger: "blur"
						// },
						// ]
					},
					{
						label: '用户性别',
						prop: 'sex',
						type: 'radio',
						// rules: [
						// 	{
						// 		required: true,
						// 		message: '请选择性别',
						// 		trigger: 'blur'
						// 	}
						// ],
						dicData: [
							{
								label: '男',
								value: '1'
							},
							{
								label: '女',
								value: '0'
							}
						],
						hide: true
					},
					{
						label: '账号状态',
						prop: 'status',
						slot: true,
						type: 'switch',
						dicData: [
							{
								label: '关闭',
								value: 'DISABLE'
							},
							{
								label: '开启',
								value: 'ENABLE'
							}
						]
					}
				]
			},
			display: true,
			addIsShow: false,
			editIsShow: false,
			form: {},
			query: {},
			loading: true,
			rolesTree: [],
			rolesKeys: [],
			box: false,
			page: {
				pageSize: 10,
				currentPage: 1,
				total: 0
			},
			option: {
				size: 'mini',
				tip: false,
				border: true,
				index: true,
				rowKey: 'userId',
				height: 'auto',
				// calcHeight: 380,
				dialogType: 'dialog',
				addBtn: false,
				editBtn: false,
				viewBtn: false,
				align: 'center',
				column: [
					{
						label: '账号',
						prop: 'account',
						fixed: true
					},
					{
						label: '姓名',
						prop: 'name',
						width: 150
					},
					{
						label: '电话',
						prop: 'phone',
						width: 150
					},
					{
						label: '账号状态',
						prop: 'status',
						slot: true,
						type: 'switch',
						width: 120,
						dicData: [
							{
								label: '关闭',
								value: 'DISABLE'
							},
							{
								label: '开启',
								value: 'ENABLE'
							}
						]
					},
					{
						label: '是否是客服',
						prop: 'customerService',
						slot: true,
						type: 'switch',
						width: 120,
						dicData: [
							{
								label: '否',
								value: false
							},
							{
								label: '是',
								value: true
							}
						]
					},
					{
						label: '创建时间',
						prop: 'createTime',
						width: 180,
						display: false
					}
				]
			},
			data: [],
			roleId:3
		};
	},
	computed: {
		...mapGetters(['permission', 'userInfo']),
		permissionList() {
			return {
				delBtn: this.vaildData(this.permission['/mall-cloud-system/sellerMgr/delete'], false)
			};
		}
	},
	methods: {
		addUser() {
			//新增用户处理弹窗
			this.addIsShow = true;
			console.log(this.userFrom);
		},
		rowEdit(row) {
			//行编辑事件
			this.getTree()
			this.editIsShow = true;
			this.$nextTick(() => {
				this.editUserFrom.account = row.account;
				this.editUserFrom.name = row.name;
				this.editUserFrom.phone = row.phone;
				this.editUserFrom.email = row.email;
				this.editUserFrom.birthday = row.birthday;
				this.editUserFrom.sex = row.sex;
				this.editUserFrom.status = row.status;
				this.editUserFrom.userId = row.userId;
			});
		},
		btnSubmit() {
			console.log(this.userFrom);
			this.$refs['diaformRef'].validate(valid => {
				if (valid) {
					this.addLoadU = true;
					if (this.userFrom.birthday) {
						let value = this.userFrom.birthday;
						let date = new Date(value.replace(/-/, '/'));
						//将时间转时间戳
						let birthday = date.getTime();
						let currentTimestamp = new Date().getTime();
						if (birthday > currentTimestamp) {
							this.addLoadU = false;
							this.$message.error('出生日期不能超过当前日期');
							return;
						}
					} else {
						this.userFrom.birthday = '';
					}
					add(this.userFrom).then(res => {
						if (res.data.code == 200) {
							this.addLoadU = false;
							this.loading = true;
							this.$message({
								type: 'success',
								message: '新增成功'
							});
							this.onLoad(this.page);
						} else {
							this.$message({
								type: 'error',
								message: res.data.message
							});
						}
						this.addIsShow = false;
					});
				}
			});
		},
		handleEmpty() {
			this.$refs['diaformRef'].resetForm();
			this.addLoadU = false;
		},
		editBtnSubmit() {
			this.$refs['diaEditFormRef'].validate(valid => {
				if (valid) {
					this.editLoadU = true;
					if (this.editUserFrom.birthday) {
						let value = this.editUserFrom.birthday;
						let date = new Date(value.replace(/-/, '/'));
						//将时间转时间戳
						let birthday = date.getTime();
						let currentTimestamp = new Date().getTime();
						if (birthday > currentTimestamp) {
							this.editLoadU = false;
							this.$message.error('出生日期不能超过当前日期');
							return;
						}
					} else {
						this.editUserFrom.birthday = '';
					} if (!this.editUserFrom.sex){
						this.editUserFrom.sex=""
					}
					update(this.editUserFrom).then(res => {
						if (res.data.code == 200) {
							this.editLoadU = false;
							this.loading = true;
							this.$message({
								type: 'success',
								message: '编辑成功!'
							});
							this.onLoad(this.page);
						} else {
							this.$message({
								type: 'error',
								message: res.data.message
							});
						}
						this.editIsShow = false;
					});
				}
			});
		},
		editHandleEmpty() {
			this.$refs['diaEditFormRef'].resetForm();
			this.editLoadU = false;
		},
		handleSetRoles() {
			let nodes=this.$refs.tree.getCheckedNodes();
			nodes.forEach(item=>{
				this.roleId.push(item.id)
			})
			this.form.roleId = this.roleId
			console.log(nodes)
			console.log(this.form.userId);
			console.log(this.form.roleId);
			this.isDisabled = true;
			if (this.form.roleId) {
				if (this.form.userId != 1 && this.form.roleId == 1) {
					this.$message({
						type: 'warning',
						message: '不能设置超级管理员'
					});
					this.isDisabled = false;
					return;
				} else {
					if (this.form.userId && this.form.roleId) {
						setRoles(this.form.userId, this.form.roleId).then(res => {
							if (res.data.code == 200) {
								this.flag = true;
								this.$message.success('设置成功');
								this.box = false;
								this.onLoad(this.page);
								this.form = {};
							}
						});
					} else {
						return;
					}
				}
			} else {
				this.$message.error('请至少给该用户分配一个权限');
				this.isDisabled = false;
			}
		},
		// rolesChange(data, checked) {
		// 	checked.checkedKeys.push(this.roleId)
		// 	this.form.roleId = checked.checkedKeys.join(',');
		// },
		rowRoles(row) {
			this.isDisabled = false;
			this.getTree(row.roleId.split(',') )
			this.form = row;
			this.form.roleId = this.form.roleId || '';
			this.rolesKeys = row.roleId.split(',');
			this.box = true;
			this.onLoad(this.page);
		},
		getTree(roleIds){
			getRolesTree(this.userInfo.id).then(res => {
				console.log(res.data);
				let ids=roleIds
				res.data.forEach(item=>{
					roleIds.forEach((roleId,index)=>{
						if(item.id==roleId){
							ids.splice(index,1)
						}
					})
				})
				this.roleId=ids
				this.rolesTree = res.data;
			});
		},
		rowSwitchChange(row) {
			this.$confirm('是否改变该用户状态?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				if (row.status === 'ENABLE') {
					changeStatus(row.userId, 'unfreeze').then(res=>{
						if(res.data.code==200) {
							this.$message({
								type: 'success',
								message: '设置成功'
							});
							this.onLoad(this.page)
						}else {
							this.$message({
								type: 'error',
								message: res.data.message
							});
						}
					});;
				} else {
					changeStatus(row.userId, 'freeze').then(res=>{
						if(res.data.code==200) {
							this.$message({
								type: 'success',
								message: '设置成功'
							});
							this.onLoad(this.page)
						}else {
							this.$message({
								type: 'error',
								message: res.data.message
							});
						}
					});;
				}
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
				this.onLoad(this.page)
			});


		},
		customerServiceSwitchChange(row) {
			this.$confirm('是否改变该用户的客服状态?', '提示', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			}).then(() => {
				customerServiceStatus(row.userId, row.customerService).then(res=>{
					if(res.data.code==200) {
						this.$message({
							type: 'success',
							message: '设置成功'
						});
						this.onLoad(this.page)
					}else {
						this.$message({
							type: 'error',
							message: res.data.message
						});
					}
				});
			}).catch(() => {
				this.$message({
					type: 'info',
					message: '已取消操作'
				});
				this.onLoad(this.page)
			});

		},
		rowSave(row, loading, done) {
			row.position = row.positionIds;
			row.deptName = row.$deptId;
			row.repassword = row.password;
			console.log(row);
			add(row).then(
				() => {
					loading();
					this.onLoad(this.page);
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
					done()
				}
			);
		},
		rowUpdate(row, index, loading, done) {
			row.position = row.positionIds;
			update(row).then(
				() => {
					loading();
					this.onLoad(this.page);
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
					done()
				}
			);
		},
		rowDel(row) {
			this.$confirm('确定将选择数据删除?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					return remove(row.userId);
				})
				.then(() => {
					if (this.data.length == 1) {
						this.page.currentPage -= 1;
					}
					this.onLoad(this.page);
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
				});
		},
		searchReset() {
			this.keySearch = '';
			this.query = {};
			this.onLoad(this.page);
		},
		searchChange(params, done) {
			console.log(this.keySearch);
			if (this.keySearch) {
				params.name = this.keySearch;
			}else{
				return
			}
			this.query = params;
			this.page.currentPage = 1;
			this.onLoad(this.page, params, done);
		},
		rowReset(row) {
			this.$confirm('确定将选择账号的密码重置为111111?', {
				confirmButtonText: '确定',
				cancelButtonText: '取消',
				type: 'warning'
			})
				.then(() => {
					return resetPassword(row.userId);
				})
				.then(() => {
					this.$message({
						type: 'success',
						message: '操作成功!'
					});
				});
		},
		beforeOpen(done, type) {
			if (['edit', 'view'].includes(type)) {
				getUser(this.form.userId).then(res => {
					this.form = res.data.data;
					this.form.positionIds = this.form.positionIds.split(',');
				});
			}
			done();
			setTimeout(() => {
				if ('add' === type) {
					this.form.status = 'ENABLE';
				}
			}, 0);
		},
		currentChange(currentPage) {
			this.page.currentPage = currentPage;
		},
		sizeChange(pageSize) {
			this.page.pageSize = pageSize;
		},
		refreshChange() {
			this.onLoad(this.page);
		},
		onLoad(page, params = {}, done) {
			this.loading = true;
			getList(page.currentPage, page.pageSize, Object.assign(params, this.query)).then(res => {
				if (done) {
					done();
				}
				this.loading = false;
				const data = res.data;
				this.page.total = data.count;
				this.data = data.data;
				//转化字典
				this.data.forEach(ele => {
					ele.positionIds = ele.positionIds.split(',');
				});
			});
		}
	}
};
</script>

<style></style>
